from urllib.parse import quote

import dateutil
import xlwt
from django.http import HttpResponse
from requests import Response

from TaskSaas.kanban.kanban import kanban_context
from TaskSaasAPP import date_util
from web.models import Project


def export_to_excel(request, project_id):
    print('export_to_excel ..')
    # 创建工作簿对象
    workbook = xlwt.Workbook(encoding='utf-8')
    # 添加工作表
    worksheet = workbook.add_sheet('Sheet1')

    project = Project.objects.filter(id=project_id).first()
    if not project:
        return HttpResponse("项目不存在")

    kanban_data = kanban_context(None,project_id)

    # 假设我们有一些数据来导出
    data = [
        ['需求/任务池']+[i[1] for i in kanban_data['pool_list']],
        ['确认分析/分配中']+[i[1] for i in kanban_data['confirm_list']],
        ['开发中']+[i[1] for i in kanban_data['developing_list']],
        ['已完成/测试中']+[i[1] for i in kanban_data['done_list']],
        ['待发布/发版(DEV)']+[i[1] for i in kanban_data['dev_list']],
        ['已发布/发版(PROD)']+[i[1] for i in kanban_data['prod_list']],
    ]

    # 设置自动换行的样式
    style = xlwt.XFStyle()
    alignment = xlwt.Alignment()
    alignment.wrap = 1  # 自动换行
    style.alignment = alignment

    # 写入数据到工作表
    for row_idx, row in enumerate(data):
        for col_idx, col in enumerate(row):
            worksheet.write(col_idx, row_idx,col, style)

    # 设置列宽
    worksheet.col(0).width = 256 * 40  # 设置第一列宽度为30字符
    for col_idx in range(1, len(data[0])):
        worksheet.col(col_idx).width = 256 * 40  # 设置其他列宽度为15字符
    file_name = '%s_KANBAN.xls' % (project.name+'_'+date_util.get_today())
    # 编码文件名
    encoded_file_name = quote(file_name.encode('utf-8'))

    # 设置HTTP响应头
    content_disposition = 'attachment; filename*=UTF-8\'\'%s' % encoded_file_name
    response = HttpResponse(content_type='application/vnd.ms-excel')
    response['Content-Disposition'] = content_disposition

    # 保存工作簿到响应
    workbook.save(response)
    print('export end')
    print('response>>', response)
    return response
